// 导入数据库操作模块
const db = require('../db/index')
// 导入加密包
const bcrypt = require('bcryptjs')
// 导入token的包
const jwt = require('jsonwebtoken')
const config = require('../config')

// 处理函数
exports.regUser = function(req, res){
    const userinfo = req.body
    // if(!userinfo.username || !userinfo.password){
    //     return res.cc('用户名或密码不能为空！')
    // }

    // 定义SQL，查询用户名是否被占用
    const sqlstr = 'select * from ev_users where username=?'
    db.query(sqlstr, userinfo.username,(err,result) => {
        if(err){
            return res.cc(err)
        }
        if(result.length > 0){
            return res.cc('用户名已被占用')
        }
        // 正常
        userinfo.password = bcrypt.hashSync(userinfo.password,10)
        const sql = 'INSERT INTO ev_users set ?'
        db.query(sql,{username:userinfo.username,password:userinfo.password},(err,result)=>{
            if(err) return res.send({status: 1, message: err.message})
            if(result.affectedRows!==1) return res.cc('注册失败，请稍后再试！')
            res.cc('注册成功！',0)
        })
    })
}

exports.login =  function(req, res){
    const userinfo = req.body
    const sql = 'select * from ev_users where username=?'
    db.query(sql,userinfo.username,(err,result)=>{
        if(err) return res.cc(err);
        if(result.length !==1) return res.cc('登录失败！')
        const compare = bcrypt.compareSync(userinfo.password, result[0].password)
        if(!compare) return res.cc('登录失败')
        const user= {...result[0],password: '',user_pic: ''}
        const token = jwt.sign(user,config.jwtSecretKey, {expiresIn: '10h'})
        res.send({
            status: 0, 
            message: '登录成功',
            token: 'Bearer '+token,
        })
    })
    
}